package edu.chl.da.ejb.ctrl;

import edu.chl.da.ejb.core.Account;
import edu.chl.da.ejb.core.Travelagent;
import edu.chl.da.ejb.persistency.IAccountFacade;
import edu.chl.da.ejb.persistency.ITravelagentFacade;
import javax.ejb.EJB;
import javax.ejb.Stateless;

/**
 *
 * @author Max
 */
@Stateless
public class ManageAccount implements IManageAccount {

    @EJB
    IAccountFacade iaf;

    @EJB
    ITravelagentFacade itaf;


    @Override
    public boolean checkNameAvailability(String name) {
        Account account;
        account = iaf.find(name);
        if(account == null){
            return true;
        }
        return false;
    }

    @Override
    public Account getAccount(String name) {
        return iaf.find(name);
    }

    @Override
    public boolean validateAccountLogin(String username, String password) throws NullPointerException {
        if(username.equals("") || password.equals("") || username == null || password == null){
            throw new NullPointerException("Username or password is empty/null.");
        }

        // Creates a travelagent if none exsist, @my bose made me do this
        if(itaf.findAll().isEmpty()) {
            Travelagent ta = new Travelagent(); ta.setAccount("admin");
            Account a = new Account(); a.setTravelagent(ta); ta.setAccount1(a);
            a.setPassword("admin"); a.setUsername("admin"); a.setFirstname("Admin");
            a.setEmail("ADMIN@admin.com"); a.setLastname("Admin");
            itaf.create(ta);
        }
        
        if(iaf.findByUsernameAndPassword(username, password) != null){
            return true;
        }

        return false;
    }
}
